import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import store from 'store'
import {fetch} from '../data/util'

const base = url.base,
  getOpenBuildingList = request.getOpenBuildingList,
  getHbuList = request.getHbuList,
  editOpenBuild = request.editOpenBuild,
  setOpen = request.setOpen

let table
let storeData;

let sendArr = []
let selectArr = []
let resData

table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getOpenBuildingList,
  queryParams: function (params) {
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize
    }, $('#searchForm').serializeObject())
  }, ajax: function (params) {  //  自定义ajax
    $.ajax({
      url: params.url,
      type: params.type,
      contentType: params.contentType,
      headers: {
        myToken: Cookies.get('myToken')
      },
      data: params.data
    })
      .done(function (res) {
        resData = res
        console.log(resData)
        console.log("table success")

        params.success({
          total: res.object.totalRows,
          rows: res.object instanceof Array ? res.object : res.object.elements
        })

      })
  },
  columns: [
    {
      field: 'buildingName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'hobPeriod',
      title: '开盘期',
      valign: 'middle'
    }, {
      field: 'hobUnitStr',
      title: '开盘楼栋',
      valign: 'middle'
    }, {
      field: 'hobWay',
      title: '开盘方式',
      valign: 'middle',
      formatter: (index, row) => {
        if (index === 'ytj') {
          return '一体机'
        }

        if (index === 'app-ytj') {
          return '一体机+app'
        }

        return ''
      }
    }, {
      field: 'hobSpecificTime',
      title: '开盘时间',
      valign: 'middle',
      formatter: (v, r) => {
        if (r.status == 1) {
          //具体开盘
          console.log('v===>>', v)
          if (v) {
            return moment(v).format('YYYY-MM-DD HH:mm')
          } else {
            return '-'
          }
        } else if (r.status == 2) {
          //预计开盘
          console.log('hobExpectTime===>>', r.hobExpectTime)
          if (r.hobExpectTime) {
            return `预计：${moment(r.hobExpectTime).format('YYYY-MM-DD HH:mm')}`
          }
          else return '-'
        }
      }
    }, {
      field: 'hobPreTime',
      title: '预选时间',
      valign: 'middle',
      formatter: (v, r) => {
        if (v) {
          return moment(v).format('YYYY-MM-DD HH:mm')
        } else {
          return '暂无'
        }
      }
    }, {
      field: 'status',
      title: '开盘状态',
      valign: 'middle',
      formatter: (v, r) => {
        if (v == 1) {
          return '已开盘'
        } else {
          return '未开盘'
        }
      }
    }, {
      field: 'houseCount',
      title: '开盘房源',
      valign: 'middle'
    }, {
      field: 'houseRemainCount',
      title: '剩余房源数',
      valign: 'middle'
    }, {
      field: 'status',
      valign: 'middle',
      align: 'center',
      width: '240px',
      title: '操作',
      formatter: (v, r) => {
        sendArr.push(r)
        if (v === 1) {
          return (
            `<div class="btn-group">
              <button type="button" data-id="${ r.idStr }" class="btn btn-default btn-openDetail">开盘详情</button>
              <button type="button" data-id="${ r.idStr }" class="btn btn-default btn-detail">详情</button>
            </div>`
          )
        } else {
          return (
            `<div class="btn-group">
              <button type="button" data-id="${ r.idStr }" class="btn btn-default btn-open">开盘</button>
              <button type="button" data-id="${ r.idStr }" class="btn btn-default btn-openDetail">开盘详情</button>
              <button type="button" data-id="${ r.idStr }" class="btn btn-default btn-modify">修改</button>
            </div>`
          )
        }
      }
    }
  ]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
})

$('#search-btn').on('click', (e) => {
  e.preventDefault();

  console.log($('#searchForm').serializeObject())

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage: 1,
    }, $('#searchForm').serializeObject())
  })
})

//跳转至修改页
$(document).on('click', '#table .btn-modify', (e) => {
  let dataId = $(e.target).attr('data-id')
  location.href = `./modify.html?id=${dataId}`

  // //转换时间戳
  // function getDateStr(res, type) {
  //   let str = `<input class="time-picker" size="16" type="text" value="${res.getFullYear()
  //     }-${res.getMonth() + 1 > 9 ? res.getMonth() + 1 : '0' + (res.getMonth() + 1)
  //     }-${res.getDate() > 9 ? res.getDate() : '0' + res.getDate()
  //     }	&nbsp;${res.getHours() > 9 ? res.getHours() : '0' + res.getHours()
  //     }:${res.getMinutes() > 9 ? res.getMinutes() : '0' + res.getMinutes()}"
  //        readonly id="edit-${type}" edit-${type}="${Date.parse(res)}">`
  //   return str
  // }
  //
  // function getShortDate(res, type) {
  //   let str = `<input class="time-picker" size="16" type="text" value="${res.getFullYear()
  //     }-${res.getMonth() + 1 > 9 ? res.getMonth() + 1 : '0' + (res.getMonth() + 1)
  //     }"
  //        readonly id="edit-${type}" edit-${type}="${Date.parse(res)}">`
  //   return str
  // }
  //
  // e.preventDefault();
  //
  // console.log('详情');
  // store.set('storeData', storeData);
  //
  // let buildingId = sendArr[0].buildingId
  //
  // let unitsLists = []
  //
  // console.log(buildingId)
  // $.ajax({
  //   type: "GET",
  //   url: base + 'admin/house/getHouseBuildUnit.json',
  //   dataType: "json",
  //   data: {
  //     buildId: buildingId
  //   },
  //   headers: {
  //     myToken: Cookies.get('myToken')
  //   },
  // }).then(res => {
  //   let unitStrArr = []
  //   unitsLists.push(...res.object)
  //   unitsLists.forEach(k => {
  //     if (unitStrArr.indexOf(k.idStr) < 0) {
  //       let obj = {
  //         id: null,
  //         str: null
  //       }
  //       obj.id = k.idStr
  //       obj.str = k.hbuNum
  //       unitStrArr.push(obj)
  //     }
  //   })
  //   let testStr = ''
  //   unitStrArr.forEach(k => {
  //     let str = `<div class="unit-list" data-id="${k.id}">${k.str}</div>`
  //     testStr += str
  //   })
  //
  //   sendArr.forEach(k => {
  //     console.log('id====>>>', $(e.target).attr('data-id'))
  //     if ($(e.target).attr('data-id') == k.idStr) {
  //       getHouseUnit($(e.target).attr('data-id'), k.hobPeriod)
  //       let timeObj = {
  //         hobExpectTime: k.hobExpectTime ? new Date(k.hobExpectTime) : new Date(),
  //         hobSpecificTime: k.hobSpecificTime ? new Date(k.hobSpecificTime) : new Date(),
  //         hobPreTime: k.hobPreTime ? new Date(k.hobPreTime) : new Date()
  //       }
  //       if (document.querySelector('#modify-modal')) {
  //         $('#modify-modal').remove()
  //       }
  //       // let obj1={
  //       //   id: dataId || null,
  //       //     dId: $('#edit-devName').attr('edit-did'),
  //       //   buildingId: $('#edit-buildingName').attr('buildingId'),
  //       //   hobPeriod: $('#edit-hobPeriod')[0].value,
  //       //   hobUnitId: idStr,
  //       //   hobExpectTime: $('#edit-hobExpectTime').attr('edit-hobExpectTime'),
  //       //   hobSpecificTime: $('#edit-hobSpecificTime').attr('edit-hobSpecificTime'),
  //       //   hobPreTime: $('#edit-hobPreTime').attr('edit-hobPreTime') > 0 ? $('#edit-hobPreTime').attr('edit-hobPreTime') : null,
  //       //   hobPreNum: $('#edit-hobPreNum').val(),
  //       //   hobWay: $('#edit-hobWay').serializeObject().hobWay
  //       // }
  //       let str = `<div class="modal fade" id="modify-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  //                   <table>
  //                     <div class="modal-dialog" role="document">
  //                         <div class="modal-content">
  //                           <div class="modal-header">
  //                             <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  //                             <h4 class="modal-title" id="myModalLabel">修改开盘</h4>
  //                           </div>
  //                           <div class="modal-body">
  //                             ${k.devName ? `<p><span>开发商：</span><input id="edit-devName" edit-devName="${k.id}" edit-did="${k.dId}" readonly="readonly"  type="text" value="${k.devName}"></p>` : ''}
  //                             <p><span>楼盘：</span><input readonly="readonly" type="text" id="edit-buildingName" buildingId="${k.buildingId}" value="${k.buildingName}"></p>
  //                             <p><span>开盘期：</span>
  //                             <!--<input readonly="readonly" type="text" id="edit-hobPeriod" value="${k.hobPeriod}">-->
  //                             <select name="" id="edit-hobPeriod"></select>
  //                             </p>
  //                             <div id="edit-hobUnitStr"><span>选择开盘楼栋：</span><div class="hobUnitId"><strong>${testStr}</strong></div>
  //                             </div>
  //                             <p><span>预计开盘时间：</span>
  //                             ${getShortDate(timeObj.hobExpectTime, 'hobExpectTime')}
  //                             </p>
  //                             <p><span class="span-title">开盘方式：</span>
  //                                                   <span id='edit-hobWay'>
  //                                                     <input type="radio" id="price-yes" name="hobWay" value="ytj">
  //                                                        <label for="price-yes">一体机</label>
  //                                                      <input type="radio" id="price-no" name="hobWay" value="both">
  //                                                    <label for="price-no">一体机+APP</label>
  //                                                    </span>
  //                                                </p>
  //
  //                             <p><span>订单失效时间：</span>
  //                             ${getDateStr(timeObj.hobSpecificTime, 'hobSpecificTime')}
  //                             </p>
  //                             <p><span>集中开盘期限：</span>
  //                               <select name="timeLimit" id="edit-timeLimit">
  //                                 <option value="1">一天</option><option value="2">两天</option><option value="3">三天</option>
  //                                 <option value="4">四天</option><option value="5">五天</option>
  //                               </select>
  //                             </p>
  //                             <p><span>预选时间：</span>
  //                             ${getDateStr(timeObj.hobPreTime, 'hobPreTime')}
  //                             </p>
  //                             <p><span>预选房源套数：</span>
  //                             <select name="hobPreNum" id="edit-hobPreNum">
  //                               <option value="1">1</option><option value="2">2</option><option value="3">3</option>
  //                             </select>
  //                             <!--<input id="edit-hobPreNum" type="number" value="${k.hobPreNum}">-->
  //                             </p>
  //                             <p><span>无存款证明认购金额：</span><input name="subscribedAmount" id="edit-subscribedAmount"  type="text" value="${k.subscribedAmount ? k.subscribedAmount : ''}"></p>
  //                              <p><span>显示状态：</span><span style="display: inline-block"><input type="radio" id="displayState-show" name="displayState" value="1">
  //                                                        <label for="displayState-show">显示</label>
  //                                                      <input type="radio" id="displayState-hide" name="displayState" value="0">
  //                                                    <label for="displayState-hide">隐藏</label></span></p>
  //                         </div>
  //                           <div class="modal-footer">
  //                             <button type="button" id="edit-submit" class="btn btn-primary">修改</button>
  //                           </div>
  //                         </div>
  //                       </div>
  //                   </table>
  //                  </div>`
  //       $('.content-wrap').append(str)
  //
  //       let unit = k.hobUnitStr
  //       let unitArr = unit.split(',')
  //       let strToStr = ''
  //       unitArr.forEach(k => {
  //         console.log('k:', k);
  //         [...document.querySelectorAll('#modify-modal .modal-body .unit-list')].forEach(j => {
  //           if ($(j).text() == k) {
  //             // console.log($(j))
  //             $(j).addClass('unit-active')
  //           }
  //         })
  //       })
  //
  //       $('#edit-hobExpectTime').datetimepicker({format: 'yyyy-mm'}).on('changeDate', e => {
  //         let date = Date.parse(e.date)
  //         $(e.target).attr('edit-hobExpectTime', date)
  //       })
  //       $('#edit-hobSpecificTime').datetimepicker({format: 'yyyy-mm-dd hh:ii'}).on('changeDate', e => {
  //         let date = Date.parse(e.date)
  //         $(e.target).attr('edit-hobSpecificTime', date)
  //       })
  //       $('#edit-hobPreTime').datetimepicker({format: 'yyyy-mm-dd hh:ii'}).on('changeDate', e => {
  //         let date = Date.parse(e.date)
  //         $(e.target).attr('edit-hobPreTime', date)
  //       })
  //       // }
  //       $('#edit-hobPreTime').val('')
  //       $('#modify-modal').modal('show')
  //
  //       $('.unit-list').on('click', e => {
  //         $(e.target).toggleClass('unit-active')
  //       })
  //
  //       //检查选中的checkbox
  //       $('#edit-submit').on('click', () => {
  //         let idStr = '';
  //         let buildingId = $('#edit-buildingName').attr('buildingId')
  //         $.ajax({
  //           type: "POST",
  //           url: base + getHbuList,
  //           dataType: "json",
  //           data: {
  //             buildingId: buildingId
  //           },
  //           headers: {
  //             myToken: Cookies.get('myToken')
  //           },
  //         }).done(res => {
  //           $('.unit-list').each((index, element) => {
  //             if ($(element).hasClass('unit-active') && selectArr.indexOf($(element).text()) < 0) {
  //               selectArr.push($(element).text())
  //             }
  //           })
  //
  //           res.forEach(k => {
  //             // console.log('kkk:', k, selectArr)
  //             selectArr.forEach(l => {
  //               if (l == k.hbuNum) {
  //                 console.log(k)
  //                 if (idStr === '') {
  //                   idStr += k.idStr
  //                 } else {
  //                   idStr += ',' + k.idStr
  //                 }
  //               }
  //             })
  //           })
  //           console.log('resData:', resData)
  //           let data = {
  //             id: dataId || null,
  //             dId: $('#edit-devName').attr('edit-did'),
  //             buildingId: $('#edit-buildingName').attr('buildingId'),
  //             hobPeriod: $('#edit-hobPeriod')[0].value,
  //             hobUnitId: idStr,
  //             hobExpectTime: $('#edit-hobExpectTime').attr('edit-hobExpectTime'),
  //             hobSpecificTime: $('#edit-hobSpecificTime').attr('edit-hobSpecificTime'),
  //             hobPreTime: $('#edit-hobPreTime').attr('edit-hobPreTime') > 0 ? $('#edit-hobPreTime').attr('edit-hobPreTime') : null,
  //             hobPreNum: $('#edit-hobPreNum')[0].value,
  //             hobWay: checkRadio(),
  //             timeLimit: $('#edit-timeLimit').val(),
  //             subscribedAmount: $('#edit-subscribedAmount').val(),
  //             displayState: checkRadioShow()
  //           }
  //           console.log('data=====>>', data)
  //           if (!idStr) {
  //             alert('请选择开盘楼栋')
  //             return false
  //           }
  //           $.ajax({
  //             type: "POST",
  //             url: base + editOpenBuild,
  //             dataType: "json",
  //             data: data,
  //             headers: {
  //               myToken: Cookies.get('myToken')
  //             },
  //           }).then(res => {
  //             // $('#modify-modal').modal('hide')
  //             // window.location.reload()
  //           })
  //
  //         })
  //       })
  //     }
  //   })
  // })

});

//跳转至详情页
$(document).on('click', '#table .btn-detail', (e) => {
  e.preventDefault();

  console.log('详情');
  store.set('storeData', storeData);

  let id = $(e.target).attr('data-id');
  window.location.href = `./detail.html?id=${id}`
});

$(document).on('click', '#table .btn-open', e => {
  e.preventDefault()
  store.set('storeData', storeData)
  if (confirm('是否确认开盘')) {
    sendArr.forEach(k => {
      if (k.idStr == $(e.target).attr('data-id')) {
        let data = {
          hobUnitId: k.hobUnitId,
          houseBuildingUnitId: k.idStr,
          buildId: k.buildingId
        }
        $.ajax({
          type: "POST",
          url: base + setOpen,
          dataType: "json",
          data: data,
          headers: {
            myToken: Cookies.get('myToken')
          },
        }).then(res => {
          if (res.code === 0) {
            window.location.reload()
          }
        })
      }
    })
  } else {
    return
  }

})

$(document).on('click', '#table .btn-openDetail', e => {
  let url = $(e.target).attr('data-id')
  window.location.href = `./openDetail.html?id=${url}`
})

function getHouseUnit(res, selected) {
  fetch({url: '/admin/house/getHousehobPeriod.json', data: {buildId: res}}).then(res => {
    res.object.map(k => {
      $('#edit-hobPeriod').append(unitStr(k))
    })
    $('#edit-hobPeriod').val(selected)
  })
}

function unitStr(k) {
  const str = `<option value="${k}">${k}</option>`
  return str
}

function checkRadio() {
  const radioVal = $('input[type="radio"][name="hobWay"]:checked').val()
  console.log('radioVal===>>>', radioVal)
  return radioVal
}

function checkRadioShow() {
  const radioVal = $('input[type="radio"][name="displayState"]:checked').val()
  console.log('displayState===>>>', radioVal)
  return radioVal
}